import math
import time
import os
import sys

# 将工程目录加入包扫描
currPath = os.path.abspath(os.path.dirname(__file__))
srcPath = os.path.split(currPath)[0]
rootPath = os.path.split(srcPath)[0]
projectPath = os.path.split(rootPath)[0]
sys.path.append(projectPath)

from src.db.CcxDataCenterDb import CcxDataCenter
from src.db.ProdDb import ProdDb
from src.utils.LogUtils import Logger

logger = Logger()


class syncQeResult:
    def __init__(self, logger, localDb, dataCenterDb):
        self.logger = logger
        self.localDb = localDb
        self.dataCenterDb = dataCenterDb

    def __queryMaxTime__(self):
        sql = """SELECT max(last_edit_time) as last_edit_time  FROM city_invest_qe_result WHERE release_status = 1 AND `status` = 1 AND ver = 0 ORDER BY last_edit_time DESC"""
        return self.localDb.Query(sql, None)

    def __queryCityInvestQe__(self, maxTime):
        sql = """SELECT * FROM city_invest_qe_result WHERE release_status = 1 AND `status` = 1 AND ver = 0 AND 
        last_edit_time > %s"""
        if maxTime[0]["last_edit_time"] == None:
            last_edit_time = 0
        else:
            last_edit_time = maxTime[0]["last_edit_time"]
        self.logger.info("数据最大时间=======%s" % last_edit_time)
        return self.dataCenterDb.Query(sql, last_edit_time)

    def __deleteCityInvestResult__(self):
        sql = """
        delete from  city_invest_qe_result
        """
        return self.localDb.Query(sql, None)

    def __save_db__(self, data):
        insertSql = """
        REPLACE INTO  city_invest_qe_result
            (id,code,credit_code,platform_rank,platform_rank_score,year,region_id,region_rating_id,used_report,region_version,sign,param,bca_level,anchor_level,busi_risk,release_status,
            last_release_time,last_release_user,last_edit_time,last_edit_user,ver,status)
            VALUES
            (%(id)s,%(code)s,%(credit_code)s,%(platform_rank)s,%(platform_rank_score)s,%(year)s,%(region_id)s,%(region_rating_id)s,%(used_report)s,%(region_version)s,
            %(sign)s,%(param)s,%(bca_level)s,%(anchor_level)s,%(busi_risk)s,%(release_status)s,%(last_release_time)s,%(last_release_user)s,%(last_edit_time)s,%(last_edit_user)s,%(ver)s,%(status)s);
        """

        temp = []
        for i in data:
            data = {
                "id": i["id"],
                "code": i["code"],
                "credit_code": i["credit_code"],
                "platform_rank": i["platform_rank"],
                "platform_rank_score": i["platform_rank_score"],
                "year": i["year"],
                "region_id": i["region_id"],
                "region_rating_id": i["region_rating_id"],
                "used_report": i["used_report"],
                "region_version": i["region_version"],
                "sign": i["sign"],
                "param": i["param"],
                "bca_level": i["bca_level"],
                "anchor_level": i["anchor_level"],
                "busi_risk": i["busi_risk"],
                "release_status": i["release_status"],
                "last_release_time": i["last_release_time"],
                "last_release_user": i["last_release_user"],
                "last_edit_time": i["last_edit_time"],
                "last_edit_user": i["last_edit_user"],
                "ver": i["ver"],
                "status": i["status"],
            }
            temp.append(data)
        logger.info("城投数据一共%s条" % len(temp))
        self.localDb.ExecMany(insertSql, temp, 1000)


if __name__ == "__main__":
    logger = Logger()
    localDb = ProdDb(logSql=False, autocommit=True)
    dataCenterDb = CcxDataCenter(logSql=False, autocommit=True)
    t = time.perf_counter()
    logger.info("========同步城投qe数据 开始 ========")
    syncData = syncQeResult(logger=logger, localDb=localDb, dataCenterDb=dataCenterDb)
    syncData.__deleteCityInvestResult__()
    # 最大时间
    maxId = syncData.__queryMaxTime__()
    data = syncData.__queryCityInvestQe__(maxId)
    syncData.__save_db__(data)
    cast = (time.perf_counter() - t)
    m = math.floor(cast / 60)
    s = cast - m * 60
    logger.info('总耗时: %d分%.3f秒' % (m, s))
    logger.info("========同步城投qe数据 结束 ========")
